import { Button, Flex, Form, Input, Switch,Checkbox,Radio,message } from 'antd'
import { useRef, useState,useEffect } from 'react'
import type { RadioChangeEvent,GetProp } from 'antd';
import { updateVersion } from '@/apis/accessManagement/setup'
import { addVersion } from '@/apis/accessManagement/setup'

type MenuFormProps = {
    item: any
    onClose: () => void
}

const FormView: React.FC<MenuFormProps> = (props: any) => {
    // console.log(Object.keys(props.item).length)
    const [form] = Form.useForm()
    const [platformValue, setPlatformValue] = useState(3);
    const [forceChecked, setForceChecked] = useState(false);
    const [upgradeTipChecked, setUpgradeTipChecked] = useState(false);
    const [messageApi, contextHolder] = message.useMessage();

    const platformChange = (e: RadioChangeEvent) => {
        const value = e.target.value;
        setPlatformValue(value); 
        form.setFieldsValue({ platform: value }); 
    };

    const subVersion = (values:any) => {
        if (Object.keys(props.item || {}).length > 0) {
          subChangeVersion(values);
        } else {
          addNewVersion(values);
        }
      };

    // 提交新增版本
    const addNewVersion = async (params:any) => {
        // const { productName,platform,versionCode,desc,showForceUpgrade,showUpgradeTip,androidDownloadUrl,iosDownloadUrl } = params;
        const productParam = form.getFieldValue('product');
        const platformParam = form.getFieldValue('platform');
        const versionCodeParam = form.getFieldValue('version');
        const descParam = form.getFieldValue('desc');
        const forceUpgradeParam = forceChecked===true?1:2;
        const upgradeTipParam = upgradeTipChecked===true?1:2;
        const androidUrlParam = form.getFieldValue('androidUrl');
        const iosUrlParam = form.getFieldValue('IosUrl');
        console.log(params)
        try {
            const response = await addVersion({
                productName:productParam, 
                platform:platformParam,
                versionCode:versionCodeParam,
                desc:descParam,
                showForceUpgrade:forceUpgradeParam,
                showUpgradeTip:upgradeTipParam,
                androidDownloadUrl:androidUrlParam,
                iosDownloadUrl:iosUrlParam,
            });
            if (response || response.data) {
                // const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    form.resetFields(); 
                    await messageApi.open({
                        type: 'success',
                        content: '新增成功',
                        duration: 2,
                    });
                    props.onClose()
                    // window.location.reload();
                } else {
                    message.error(`提交失败: ${response?.errMsg || '未知错误'}`);
                    form.resetFields();
                }
            } else {
                message.error('响应数据格式错误');
                form.resetFields();
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    // 提交修改版本信息
    const subChangeVersion = async (params: any)=> {
        const { product,platform,version,versionCode,desc,showForceUpgrade,showUpgradeTip,androidDownloadUrl,iosDownloadUrl,IosUrl,androidUrl,...newParams } = params;
        // console.log(form.getFieldValue('forceUpgrade'))
        const productParam = form.getFieldValue('product');
        const platformParam = form.getFieldValue('platform');
        const versionIdParam = props.item.versionId;
        const versionCodeParam = form.getFieldValue('version');
        const descParam = form.getFieldValue('desc');
        const forceUpgradeParam = forceChecked===true?1:2;
        const upgradeTipParam = upgradeTipChecked===true?1:2;
        const androidUrlParam = form.getFieldValue('androidUrl');
        const iosUrlParam = form.getFieldValue('IosUrl');
        try {
            const response = await updateVersion({
                ...newParams,
                productName:productParam, 
                platform:platformParam,
                versionId:versionIdParam,
                versionCode:versionCodeParam,
                desc:descParam,
                showForceUpgrade:forceUpgradeParam,
                showUpgradeTip:upgradeTipParam,
                androidDownloadUrl:androidUrlParam,
                iosDownloadUrl:iosUrlParam,
            });
            if (response || response.data) {
                const { errCode, errMsg } = response;
                if (response?.errCode === 0) {
                    form.resetFields(); 
                    await messageApi.open({
                        type: 'success',
                        content: '修改成功',
                        duration: 2,
                    });
                    props.onClose()
                    // window.location.reload();
                } else {
                    message.error(`修改失败: ${response?.errMsg || '未知错误'}`);
                    form.resetFields();
                }
            } else {
                message.error('响应数据格式错误');
                form.resetFields();
            }
        } catch (error) {
            console.error('Error:', error);
        }
    }

    useEffect(() => {
        if (Object.keys(props.item).length > 0) {
            setPlatformValue(props.item.platform || 3);  // 设置默认值为3
            setForceChecked(props.item.showForceUpgrade === 1?true:false);
            setUpgradeTipChecked(props.item.showUpgradeTip === 1?true:false);
            form.setFieldsValue({
                product: props.item.productName,
                desc: props.item.desc,
                version: props.item.versionCode,
                androidUrl: props.item.androidDownloadUrl,
                IosUrl: props.item.iosDownloadUrl,
            })
        }
      }, [props.item]);

    useEffect(() => {
        form.setFieldsValue({ platform: platformValue });
    }, [platformValue]);

  return (<>
    {contextHolder}
    <Form form={form} labelAlign="right" labelCol={{ span: 8 }} onFinish={subVersion}>
        <h3 style={{textAlign:'center'}}>版本信息</h3>
        <Form.Item label="产品名称" name="product" rules={[{required: true, message: '请输入产品名称'}]}>
            <Input placeholder="请输入产品名称" />
        </Form.Item>
        <Form.Item label="平台" name="platform" rules={[{required: true, message: '请选择平台'}]}>
            <Radio.Group onChange={platformChange}>
                <Radio value={1}>Android</Radio>
                <Radio value={2}>Ios</Radio>
                <Radio value={3}>全部</Radio>
            </Radio.Group>
        </Form.Item>
        <Form.Item label="版本号" name="version" rules={[{required: true, message: '请输入版本号'}]}>
            <Input placeholder="请输入版本号" />
        </Form.Item>
        <Form.Item label="更新描述" name="desc" rules={[{required: true, message: '请输入更新描述'}]}>
            <Input.TextArea rows={4} maxLength={200} placeholder="请输入更新描述，最多不超过200字。"/>
        </Form.Item>
        <h3>更新升级配置</h3>
        <Form.Item label="强制更新" name="forceUpgrade">
            <Switch checked={forceChecked} onChange={(forceChecked) => setForceChecked(forceChecked)}/>
        </Form.Item>
        <Form.Item label="更新提示" name="upgradeTip">
            <Switch checked={upgradeTipChecked} onChange={(upgradeTipChecked) => setUpgradeTipChecked(upgradeTipChecked)}/>
        </Form.Item>
        <Form.Item label="安卓下载地址" name="androidUrl" rules={[{required: true, message: '请输入安卓下载地址'}]}>
            <Input placeholder="请输入安卓下载地址" />
        </Form.Item>
        <Form.Item label="IOS下载地址" name="IosUrl" rules={[{required: true, message: '请输入IOS下载地址'}]}>
            <Input placeholder="请输入IOS下载地址" />
        </Form.Item>
        <Form.Item>
            <Flex justify="center" align="center">
            <Button type="primary" htmlType="submit">提交</Button>
            <Button style={{ marginLeft: 10 }} onClick={props.onClose}>返回</Button>
            </Flex>
        </Form.Item>
    </Form>
  </>)
}

export default FormView